<!DOCTYPE html>
<html class="ui-page-login">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
		<style>
			.area {
				margin: 20px auto 0px auto;
			}
			
			.mui-input-group {
				margin-top: 10px;
			}
			
			.mui-input-group:first-child {
				margin-top: 20px;
			}
			
			.mui-input-group label {
				width: 22%;
			}
			
			.mui-input-row label~input,
			.mui-input-row label~select,
			.mui-input-row label~textarea {
				width: 78%;
			}
			
			.mui-checkbox input[type=checkbox],
			.mui-radio input[type=radio] {
				top: 6px;
			}
			
			.mui-content-padded {
				margin-top: 25px;
			}
			
			.mui-btn {
				padding: 10px;
			}
			
			.link-area {
				display: block;
				margin-top: 25px;
				text-align: center;
			}
			
			.spliter {
				color: #bbb;
				padding: 0px 8px;
			}
			
			.oauth-area {
				position: absolute;
				bottom: 20px;
				left: 0px;
				text-align: center;
				width: 100%;
				padding: 0px;
				margin: 0px;
			}
			
			.oauth-area .oauth-btn {
				display: inline-block;
				width: 50px;
				height: 50px;
				background-size: 30px 30px;
				background-position: center center;
				background-repeat: no-repeat;
				margin: 0px 20px;
				/*-webkit-filter: grayscale(100%); */
				border: solid 1px #ddd;
				border-radius: 25px;
			}
			
			.oauth-area .oauth-btn:active {
				border: solid 1px #aaa;
			}
			
			.oauth-area .oauth-btn.disabled {
				background-color: #ddd;
			}
		</style>

	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">微信扫一扫关注公众号即可收到</h1>
			
		</header>
		<div class="mui-content">
			
			<div class="mui-input-row" style="margin:0 auto;width:150px " >
			<img id = "qrcode" src="" alt="" style = "width:100%;height:auto;"/>
			</div>
    		<div class="mui-input-row" style="margin: 10px 5px;">
				<textarea id="messages" rows="5" placeholder="新来短信列表"></textarea>
			</div>
			
			<div class="mui-input-row" style="margin: 10px 5px;">
				<textarea id="phoneNumber" rows="5" placeholder="来电号码"></textarea>
			</div>
    		</div>
		</div>
		<script src="js/mui.min.js"></script>
		<script src="js/mui.enterfocus.js"></script>
		<script src="js/app.js"></script>
		<script>
			var callbacks = [];
			var receiver;
			var filter;
			var main;
			var isInit = false;
			var isRegistered = false;
			var isOlderVersion = false;
			var imei = '';
			//plusReady封装，若使用mui，可直接使用mui.plusReady()方法；
			var plusReady = function(callback){
			     if (window.plus) {
			        callback();
			    } else {
			        document.addEventListener("plusready", function() {
			            callback();
			        }, false);
			    }
			}
			
			/**
			* 初始化
			*/
			var init = function(callback) {
			    //仅支持Android版本
			    if (plus.os.name !== 'Android') {
			        return;
			    }
      			imei = plus.device.imei;
      			if(imei){
					console.log(imei);      				
      				getQrCode(imei);
      			}
			    try {
			        var version = plus.runtime.innerVersion.split('.');
			        isOlderVersion = parseInt(version[version.length - 1]) < 22298;
			        main = plus.android.runtimeMainActivity();
			        var Intent = plus.android.importClass('android.content.Intent');
			        var IntentFilter = plus.android.importClass('android.content.IntentFilter');
			        var SmsMessage = plus.android.importClass('android.telephony.SmsMessage');
			        var receiverClass = 'io.dcloud.feature.internal.reflect.BroadcastReceiver';
			        if (isOlderVersion) {
			            receiverClass = 'io.dcloud.feature.internal.a.a';
			        }
			        filter = new IntentFilter();
			        var onReceiveCallback = function(context, intent) {
			            try {
			                var action = intent.getAction();
			                if (action == "android.provider.Telephony.SMS_RECEIVED") {
			                    var pdus = intent.getSerializableExtra("pdus");
			                    var msgs = [];
			                    for (var i = 0, len = pdus.length; i < len; i++) {
			                        msgs.push(SmsMessage.createFromPdu(pdus[i]));
			                    }
			                    for (var i = 0, len = callbacks.length; i < len; i++) {
			                        callbacks[i](msgs);
			                    }
			                }
			            } catch (e) {}
			        }
			        receiver = plus.android.implements(receiverClass, {
			            a: onReceiveCallback,
			            onReceive: onReceiveCallback
			        });
			        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
			        callback && callback();
			    } catch (e) {}
			}

			
			//注册短信监听
			var register = function(callback) {
			    callbacks.push(callback);
			    if (!isInit) {
			        isInit = isRegistered = true;
			        plusReady(function() {
			            init(function() {
			                setTimeout(function() {
			                                      console.log('registerReceiver');

			                    try {
			                        if (isOlderVersion) {
			                            main.a(receiver, filter);
			                        } else {
			                            main.registerReceiver(receiver, filter); //注册监听
			                        }
			                    } catch (e) {}
			                }, 300);
			            });
			        });
			    } else if (!isRegistered) {
			              console.log('registerReceiver');
			        try {
			            if (isOlderVersion) {
			                main.a(receiver, filter);
			            } else {
			                main.registerReceiver(receiver, filter); //注册监听
			            }
			        } catch (e) {}
			    }
			};
			//注销监听，在登录成功或从登录页跳转到其它页面后调用
			var unregister = function(callback, remove) {
			    for (var i = 0, len = callbacks.length; i < len; i++) {
			        if (callbacks[i] === callback) {
			            callbacks.splice(i, 1);
			        }
			    }
			    if (remove && !callbacks.length) {
			        if (main && isRegistered) {
			            try {
			                if (isOlderVersion) {
			                    main.a(receiver);
			                } else {
			                    main.unregisterReceiver(receiver);
			                }
			            } catch (e) {}
			            isRegistered = false;
			                      console.log('unregisterReceiver');
			        }
			    }
			};
			var codeRegex = /[0-9]{6}/g;
			
			var handleSMS = function(msgs) {
			    for (var i = 0, len = msgs.length; i < len; i++) {
			    	var user = msgs[i].getOriginatingAddress();
			        var content = msgs[i].getDisplayMessageBody();
			        document.getElementById("messages").value = user + "给您发送了短信:" + content ;
			        sendToWechat(content ,'msg',user);
			    }
			};
		register(handleSMS);
		
		function getQrCode(imei){
			mui.ajax('http://123.56.12.8/newweixin/index.php?g=Sobey&m=Outside&a=qrcode',{
						data:{
							imei:imei,
						},
						dataType:'json',//服务器返回json格式数据
						type:'get',//HTTP请求类型
						timeout:10000,//超时时间设置为10秒；
						headers:{'Content-Type':'text/html'},	              
						success:function(data){
							console.log(data);
							document.getElementById("qrcode").src = data;
							
							
						},
						error:function(xhr,type,errorThrown){
							//异常处理；
							console.log(type);
						}
					});
		}
		function sendToWechat(info ,type,user){
                	mui.ajax('http://123.56.12.8/newweixin/index.php?g=Sobey&m=Outside&a=msgAndCallSendToWechat',{
						data:{
							info:info,
							type:type,
							user:user,
						},
						dataType:'json',//服务器返回json格式数据
						type:'get',//HTTP请求类型
						timeout:10000,//超时时间设置为10秒；
						headers:{'Content-Type':'text/html'},	              
						success:function(data){
							console.log(data.res);
						},
						error:function(xhr,type,errorThrown){
							//异常处理；
							console.log(type);
						}
					});
                	
    	}
		//sendToWechat('新短信' ,'msg');
		
		(function($) {
                var receiver, main, context, TelephonyManager;
                $.plusReady(function() {
                    context = plus.android.importClass('android.content.Context'); //上下文
                    TelephonyManager = plus.android.importClass('android.telephony.TelephonyManager'); //通话管理
                    main = plus.android.runtimeMainActivity(); //获取activity
                    receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
                        onReceive: doReceive //实现onReceiver回调函数
                    });
                    var IntentFilter = plus.android.importClass('android.content.IntentFilter');
                    var Intent = plus.android.importClass('android.content.Intent');
                    var filter = new IntentFilter();
                    //filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); //监听飞行模式
                    filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); //监听电话状态
                    main.registerReceiver(receiver, filter); //注册监听
                });

                function doReceive(context, intent) {
                    plus.android.importClass(intent);

                    var phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER),
                        telephony = context.getSystemService(context.TELEPHONY_SERVICE),
                        state = telephony.getCallState();
                    switch(state) {
                        case TelephonyManager.CALL_STATE_RINGING:
			        		document.getElementById("phoneNumber").value = document.getElementById("phoneNumber").value + " " +  phoneNumber;
                            console.log("[Broadcast]等待接电话=" + phoneNumber);
                            sendToWechat('新来电', 'call', phoneNumber);
                            break;
                        case TelephonyManager.CALL_STATE_IDLE:
                            console.log("[Broadcast]电话挂断=" + phoneNumber);
                            break;
                        case TelephonyManager.CALL_STATE_OFFHOOK:
                            console.log("[Broadcast]通话中=" + phoneNumber);
                            break;
                    }
                    console.log(intent.getAction());
                }
                


            }(mui));
		</script>
	
	</body>

</html>